<template>
    <Timer @toggle-recommend="onToggleRecommend"></Timer>
    <div id="chart-box" class="chart-box" ref="charts">
        <img id="shuiying" :src="share_tlogo" />
        <div class="chart-div" :class="{ max: maxChart }" :id="cid" @mousedown="down">
            <div class="logo">
                <img class="logo-img" src="@/assets/logo2.png" />
            </div>
            <Vols></Vols>
        </div>
        <div class="move" @click="onMove" ref="move" v-show="showMoveBtn">
            <span class="iconfont icon-double-left-1"></span>
        </div>

        <div class="new-pot" ref="newspot" id="infopot" v-show="showInfoCir && kline.curCoin?.tokenAddress"
            @click="onPopInfo" :class="{ has: hasInfo }">
            <!-- <img src="@/assets/money.png" /> -->
        </div>
        <!-- <div class="info-pot" id="infopot" v-if="showInfoCir" @click="onPopInfo" :class="{ has: hasInfo }"
            :style="potStyle">
            <img src="@/assets/money.png" />
        </div> -->
        <!-- <div class="logo">
            <img class="logo-img" src="@/assets/logo2.png" />
        </div> -->
        <TableLink id="tablelink" class="tb-link" :style="tables.link"></TableLink>
        <!-- <TableNews :show="newsShow" @hide="hideNews">
        </TableNews> -->
        <TableBS page="index" :pot="tables.bs" :item="curItem" @hide="onBSHide"></TableBS>
        <TableMore page="index" :pot="tables.more" :list="moreList" @hide="onMoreHide"></TableMore>
        <TableRecommend></TableRecommend>
        <Loading v-if="loading"></Loading>
        <div class="tool-tips" v-show="toolTips.length">
            <div class="t-tip c-title-5" v-for="i in toolTips" v-html="i"></div>
        </div>
        <TableNews></TableNews>
        <JLock :close="true"></JLock>
        
    </div>
</template>

<script lang="ts" setup>
import share_tlogo from "@/assets/share_tlogo.png"
import { onMounted, watch, ref, reactive, computed, onActivated, onDeactivated, onBeforeMount } from "vue";
import {
    Bus,
    CHART_KLINE_COMPLETE,
    CHART_KLINE_GOON,
    CHART_KLINE_SUBSCRIBE,
    CHART_KLINE_SUBSCRIBE_TIME,
    CHART_KLINE_UNSUBSCRIBE,
    CHART_KLINE__ITEM,
    CHART_KLINE__LIST,
    CONN_BIG_AMOUNT,
    CONN_FLUCTUATION,
    CONN_SIGNAL,
    CONN_STABLE_CURRENCY,
    INDICATOR_FUNDS,
    INDICATOR_MA,
    INDICATOR_TOGGLE,
    INDICATOR_TREND,
    INDICATOR_VOL,
    INDICATOR_WAVE,
    KLINE_CLEAR,
    KLINE_RESET,
    START_CONN,
    SizeChart,
    TICK
} from "@/connetion/Bus";
import { Conn } from "@/connetion/Conn";
import { get } from "@/comm/request";
import { URL_BUY_EQUITY, URL_CAPITAL_EQUITY, URL_KLINE_DATA, URL_SIGNAL_LIST, URL_SIGNAL_RECOMMEND } from "@/comm/api";
import { useKline } from "@/stores/kline";
import { maskHash, sleep, sortList } from "@/comm/tooler";
import { customStyle } from "./customStyle";
import { formatBigNumber, formatTimestamp, toChartData } from "@/comm/format";
import { drawAction, drawSignal, hitAction, hitSignal } from "./draw";
import { useActivity } from "@/stores/activity";
import { useCore } from "@/hooks/useCore";
import { sign } from "crypto";
import { useSignal } from "@/stores/signal";
import { useIndicator } from "@/stores/indicator";
import Loading from "./loading/index.vue";
import { createFundRateIndicator, createWaveIndicator, initChartConfig, removeFundRateIndicator, removeWaveIndicator, createCustomColorIndicator } from "./config";
import i18n from "@/locals";
import { useChart } from "@/hooks/useChart";
import JCheckbox from "@/components/j-checkbox/index.vue";
import JButton from "@/components/j-button/index.vue";
import JLock from "@/components/j-lock/index.vue";
import Timer from "./component/timer.vue";
import { useComm } from "./comm";
import { onUnmounted } from "vue";
import { useRoute } from "vue-router";
import TableLink from "./component/tableLink.vue"
import TableBS from "./component/tableBS.vue"
import TableMore from "./component/tableMore.vue"
import Vols from "./component/vols.vue"
// import TableNews from "./component/tableNews.vue"
import TableRecommend from "./component/tableRecommend.vue"
import TableNews from "./component/tableNews.vue"

import { type } from "os";
import DomDrag from "@/comm/DomDrag";
import { useLayout } from "@/stores/layout";
import { useUser } from "@/stores/user";
import { useAccount } from "@/stores/account";
import { useLock } from "@/hooks/useLock";
const { init, registerOverlay, registerFigure, getFigureClass, getSupportedFigures, registerIndicator } = (window as any)["klinecharts"];
let changeTimers: any[] = [];
const core = useCore();
const signal = useSignal();
const indicator = useIndicator();
const activity = useActivity();
const kline = useKline();
// const loading = ref(false)
const move = ref<any>();
const newspot = ref<any>()
const cid = ref("chart_" + (Math.random() + "").split(".").pop());
const { toolTips, resizeView, start, end, reset, onMove, loading, checkInit, getYAxisWidth, resizeChart, showMoveBtn, infoViewData, getChartList } = useComm(cid.value, move, clickEvent, newspot);
const route = useRoute();
const charts = ref(null);


let ctid = 0;
// const recommends = computed(() => {
//     var t = [...kline.recommendations];
//     t.sort((a: any, b: any) => {
//         return Math.abs(a.bias144) > Math.abs(b.bias144) ? 1 : -1;
//     });
//     return t;
// });
const curItem = ref<any>(null);
const moreList = ref();
const newsShow = ref(false)
const layout = useLayout();
const { unlock } = useLock();
// const canLook = ref(true);
const account = useAccount();


// visibility: "visible", "hidden"
// pointerEvents: "none",
// const potStyle = computed(() => {
//     return {
//         transform: `translate(${infoViewData.x}px, ${infoViewData.y}px)`,
//         opacity: infoViewData.opacity,
//         width: "20px",
//         height: "20px",
//         left: "-10px",
//         top: "0px"
//     };
// });

watch(() => layout.maxChart, () => {
    setTimeout(() => {
        resizeView()
    }, 60);
});

const hasInfo = ref(true);
const onPopInfo = () => {
    console.log('触发打开持仓')
    hasInfo.value = false;
    newsShow.value = true
}
const hideNews = (e: any) => {
    console.log('触发隐藏持仓')
    newsShow.value = false
    if (e) {
        document.removeEventListener('click', e)
    }
}

const maxChart = computed(() => layout.maxChart);

const showInfoCir = computed(() => {
    if (kline.curInterval) {
        return kline.curInterval.name !== "S1";
    }
    return false;
});

const tables = reactive({
    bs: {
        visibility: "hidden",
        x: -12000,
        y: 0
    },
    more: {
        x: -12000,
        y: 0
    },
    link: {
        x: -12000,
        y: 0
    }
});


const onToggleRecommend = async () => {
    kline.TableRecommend = !kline.TableRecommend;
    if (kline.TableRecommend) {
        kline.getRecommendations(false);
    }
};

const onBSHide = () => {
    tables.bs.x = -1200;
};

const onMoreHide = () => {
    tables.more.x = -1200;
};

function down() {
    onBSHide();
    onMoreHide();
}

function clickEvent(e: any, list: any[], isPress: boolean) {
    console.log(list, e, "0000");

    isPress = true;

    if (list) {
        if (list.length == 1) {
            if (isPress) {
                tables.bs.x = e.x;
                tables.bs.y = e.y;
            } else {
                tables.bs.x = -1200;
            }
            curItem.value = list[0].origin;
            console.log("#####curItem", curItem.value);
            clearTimeout(ctid);
            ctid = window.setTimeout(() => {
                curItem.value = null;
            }, 3000);
        } else {
            moreList.value = list;
            if (isPress) {
                tables.more.x = e.x;
                tables.more.y = e.y;
            } else {
                tables.more.x = -1200;
            }
            curItem.value = null;
        }
    }
    console.log("#####curItem", curItem.value);
    console.log('点击展开链上活动', list)
    // if(list.length == 0){
    //     tables.bs.left = "-1200px";
    // }
    // else{
    //     console.log(tbBS.value, "tab")
    //     tables.bs.left = e.x + "px";
    //     tables.bs.top = e.y - tbBS.value.height + "px";
    // }
}

// let chart: any;
let hasInit = false;

function inKeepAlive() {
    return route.name == "home";
}

// setTimeout(() => {
//     let t = activity.getEventRange(kline.curCoin.tokenAddress);
//     console.log("-------------", t)
// }, 6000);

onActivated(async () => {
    console.log("##jsz", "chart onActivated", cid.value);
    // if (inKeepAlive()) {
    await startInit();
    resizeChart();
    // }
});

onDeactivated(() => {
    console.log("##jsz", "chart onDeactivated", route.name);
    end();
    hasInit = false;
});

const initKlineData = async () => {
    console.error("等待初始化表格开始---start");
    loading.value = true;
    for (let i = 0; i < 20; i++) {
        console.error("等待初始化表格---" + i);
        let suc = await resetTimer();
        if (suc) {
            break;
        }
        await sleep(300);
    }
    loading.value = false;
    console.error("等待初始化表格完成---over");
    Bus.emit(CHART_KLINE_GOON, kline.param);
};

const resetTimer = async () => {
    if (!checkInit()) {
        console.log("wait chart init");
        return false;
    }
    return true;
};

const cancelTimer = () => {
    Bus.emit(CHART_KLINE_UNSUBSCRIBE);
};

defineExpose({
    initKlineData,
    cancelTimer
});

onBeforeMount(async () => {
    await initChartConfig();
});

async function startInit() {
    if (hasInit) return;

    while (!document.getElementById(cid.value)) {
        console.log("等待表格元素加载");
        await sleep(90);
    }

    if (route.name == "home") {
        kline.readLastData();
    } else if (route.name == "coin") {
        kline.changeCoinToDay(route.params.id + "");
    }

    await core.upateHistory();
    console.error("jsz", "start");
    // await start();
    await reset()

    // setTimeout(() => {
    //     let num = getYAxisWidth();
    //     tables.link.right = num + 10 + "px";
    // }, 900);
    hasInit = true;
    // Bus.emit(START_CONN, "初始化表格完成");
    // Bus.emit(CHART_KLINE_GOON, kline.param);

    //首页则重新获取上次数据
    Bus.emit(CHART_KLINE_COMPLETE, kline.param);
}

onMounted(async () => {
    console.log("##jsz", "chart onMounted", cid.value);
    // if (!inKeepAlive()) {
    await startInit();
    Bus.on(SizeChart, () => {
        console.log("改变尺寸")
        resizeView();
    });

    // const targetNode: any = charts.value;
    // const config = { attributes: true, childList: true, subtree: true, attributeFilter: ['style'] };
    // const callback = function (mutationsList: any, observer: any) {
    //     for (let mutation of mutationsList) {
    //         if (mutation.type === 'childList') {
    //             console.log('A child node has been added or removed.');
    //         }
    //         else if (mutation.type === 'attributes') {
    //             console.log('The ' + mutation.attributeName + ' attribute was modified.');
    //         }
    //     }
    // };
    // const observer = new MutationObserver(callback);
    // observer.observe(targetNode, config);
});

onUnmounted(() => {
    console.log("##jsz", "chart onUnmounted", route.name);
    end();
});
</script>

<style lang="less" scoped>
@import url("./index.less");
</style>
